<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 style="text-align: center;">用户注册</h2>
      <el-form :model="form" :rules="rules" ref="registerForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item class="center-btn">
          <el-button type="primary" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
      <p style="text-align: center; margin-top: 10px;">
        <router-link to="/login">已有账号？去登录</router-link>
      </p>
    </el-card>
  </div>
</template>

<script setup>
import { ref} from 'vue'
import { ElMessage } from 'element-plus'
import { register } from '../api/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const form = ref({ username: '', email: '', password: '' })

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度在3到15个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ]
}

const registerForm = ref()

async function handleRegister() {
  try {
    // 触发表单验证
    await registerForm.value.validate()

    const res = await register(form.value)
    ElMessage.success('注册成功')
    router.push('/login')
  } catch (err) {
    ElMessage.error('注册失败，请检查输入或重试')
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('../assets/login-bg.jpg') no-repeat center center fixed;
  background-size: cover;
  backdrop-filter: blur(2px);
}
.login-card {
  width: 400px;
  background-color: rgba(255, 255, 255, 0.9);
}
.center-btn .el-form-item__content {
  justify-content: center;
}
</style>